import Application from 'koa';
import { AssertionError } from 'assert';
import { CodeState } from './send';

/**
 *
 * 捕获错误 将错误转换为另外格式返回
 * @param app Application
 */
export default function catchError(app: Application) {
    app.use(async (ctx, next) => {
        try {
            await next();
            if (typeof ctx.body === 'string') {
                ctx.sendFM(ctx.body);
            }
        } catch (error: any) {
            if (error.status === 401 || error.status === '401')
                ctx.send({
                    status: CodeState.AuthenticationFAILED,
                    msg: '登陆过期，请重新登陆',
                });
            else if (error instanceof AssertionError) ctx.sendFM(error.message);
            else if (error instanceof Error) ctx.sendFM(error.message);
            else if (typeof error === 'string') ctx.sendFM(error);
            else {
                ctx.sendFM('未知错误');
            }
        }
    });
}
